package io.openmessaging.utils;

import java.nio.ByteBuffer;

/**
 * @author cuijd    2021/9/17 9:28
 */
public interface Strings {
    public static void main(String[] args) {
        System.out.println(format(1024));
        System.out.println(format(7 * 1024));
        System.out.println(format(78 * 1024));
        System.out.println(format(5 * 1024 * 1024));
        System.out.println(format(50 * 1024 * 1024));
        System.out.println(format(50L * 1024 * 1024 * 1024));
    }

    static String format(Number size) {
        return format(size, "b");
    }

    static String format(ThreadLocalLongAdder size) {
        return format(size.longValue(), "b");
    }

    static String format(Number size_, String suffix) {
        long size = size_.longValue();
        String result = size < 10 * 1024 ? size + "  " :
                size < 10 * 1024 * 1024 ? (size >> 10) + " k" :
                        size < 10L * 1024 * 1024 * 1024 ? (size >> 20) + " m" : (size >> 30) + " g";
        return leftPad(result, 6) + suffix;
    }

    static String leftPad(Object o, int length) {
        String s = o == null ? "" : o.toString();
        if (s.length() >= length)
            return s;
        StringBuilder sb = new StringBuilder(length);
        while (sb.length() < length - s.length())
            sb.append(' ');
        sb.append(s);
        return sb.toString();
    }

    static String print(ByteBuffer buf, int length) {
        StringBuilder s = new StringBuilder("[");
        for (int i = 0; i < length; i++) {
            s.append(buf.get(buf.position() + i) & 0xff).append(" ");
        }
        return s.toString();
    }

    static StringBuilder append(Object... params) {
        StringBuilder sb = new StringBuilder();
        for (Object o : params) {
            sb.append(o);
        }
        return sb;
    }
}
